<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NButton,
  NImage,
  NInput,
  NLayout,
  NLayoutContent,
  NFlex, useMessage, NTag, NAvatar
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import {formatDate, getToken, renderIcon} from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import default_image from "@/assets/images/mz.jpg";
import { exportToExcel } from '@/utils/exportUtils'
const base_path = import.meta.env.VITE_BASE

defineOptions({ name: '划扣消费明细' })
const instance = getCurrentInstance();
const nameFromInstance = instance?.type.name;

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const message = useMessage()

const data = reactive({
  uploadAction: base_path+'/system/base/userimg',
  token: getToken(),
  goods_all:[],
})

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '支付流水',
  initForm: {},
  doCreate: api.createCouponUse,
  doUpdate: api.updateCouponUse,
  doDelete: api.deleteCouponUse,
  refresh: () => $table.value?.handlerefresh(),
})


onMounted(() => {
  $table.value?.handleSearch()
})

const handleExport = async () => {
  try {
    // 显示加载状态
    const loading = message.loading('正在准备导出数据...', { duration: 0 })

    // 获取表格数据
    const { data: tableData } = await api.getOrderData({
      ...queryItems.value,
      is_export:1
    })

    if (!tableData || tableData.length === 0) {
      message.warning('没有数据可以导出')
      return
    }

    // 处理数据格式
    const exportData = tableData.map(item => ({
      分类: item.type_name,
      类型: item.category_name,
      卡项名称: item.title,
      服务人数: item.people,
      缴费次数: item.orders_cnt,
      医生次数: item.cases_time,
      销售数量: item.sale_cnt,
      初诊: item.first_cnt,
      复诊: item.second_cnt,
      再消费: item.next_cnt,
      实收: item.price,
      定金: item.czj,
      券: item.quan,
      欠款金额: item.qk_price,
      消费总额: item.all_price
    }))

    // 导出Excel
    exportToExcel(exportData, `划扣消费明细_${formatDate(new Date())}`)
    message.success('导出成功')
    loading?.destroy()
  } catch (error) {
    console.error('导出失败:', error)
    message.error('导出失败: ' + error.message)
  } finally {
    loading?.destroy()
  }
}

const columns = [
  {
    title: '分类',
    key: 'type',
    width: 100,
    align: 'center',
    render(row) {
      return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => row.type_name })
    },
  },{
    title: '类型',
    key: 'category_name',
    width: 60,
    align: 'center',
    render(row) {
      return h(NTag, { type: 'error',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => row.category_name })
    },
  },
    {
    title: '图片/卡项名称',
    key: 'image',
    width: '350',
    align: 'left',
      fixed: 'left',

    render(row) {

      return h(NFlex, {},
        [h(NAvatar, {
          src: row.image,
          fallbackSrc: default_image,
          round: true,
          size: "medium",
        }), h(NButton, {
          size: "medium",
          dashed: true,
          type: "primary",
        }, {
          default: () => (row.title)
        })]
      )

    },
  },
    {
    title: '服务人数',
    key: 'people',
    width:80,
    align: 'center',
  },
  {
    title: '缴费次数',
    key: 'orders_cnt',
    width:80,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '医生次数',
    key: 'cases_time',
    width:80,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '销售数量',
    key: 'sale_cnt',
    width:80,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '初诊',
    key: 'first_cnt',
    width:80,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '复诊',
    key: 'second_cnt',
    width:80,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '再消费',
    key: 'next_cnt',
    width:80,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '实收',
    key: 'price',
    width:80,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '定金',
    key: 'czj',
    width:80,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '券',
    key: 'quan',
    width:80,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '欠款金额',
    key: 'qk_price',
    width:80,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '消费总额',
    key: 'all_price',
    width:80,
    align: 'center',
    ellipsis: { tooltip: true },
  },
]

function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
const datetimeRange = ref()
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}
</script>

<template>
  <NLayout has-sider wh-full>
    <NLayoutContent style="background: transparent;margin-left: 20px;">
      <CommonPage show-footer title="划扣消费明细">
        <template #action>
          <NButton type="info" @click="handleExport">
            <TheIcon icon="material-symbols:download" :size="18" class="mr-5" />导出Excel
          </NButton>
        </template>
        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getOrderData"
          :scroll-x="1200"

        >
          <template #queryBar>

            <QueryBarItem label="项目名称" :label-width="80">
              <NInput
                v-model:value="queryItems.title"
                clearable
                type="text"
                placeholder="项目名称"
                style="width: 200px;"
              />
            </QueryBarItem>
            <QueryBarItem label="付款时间" :label-width="70">
              <NDatePicker
                  v-model:value="datetimeRange"
                  type="datetimerange"
                  clearable
                  placeholder="请选择时间范围"
                  @update:value="handleDateRangeChange"
              />
            </QueryBarItem>

          </template>
        </CrudTable>


      </CommonPage>


    </NLayoutContent>
  </NLayout>


  <!-- 业务页面 -->
</template>
